package com.ruoyi.project.system.file.controller;

import java.io.IOException;
import java.util.List;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.project.system.equipment.domain.Equipment;
import com.ruoyi.project.system.equipment.service.IEquipmentService;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.system.user.service.IUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.system.file.domain.File;
import com.ruoyi.project.system.file.service.IFileService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件Controller
 * 
 * @author ruoyi
 * @date 2022-02-18
 */
@Controller
@RequestMapping("/system/file")
public class FileController extends BaseController
{
    private String prefix = "system/file";

    @Autowired
    private IFileService fileService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IEquipmentService iEquipmentService;


    //文件上传
    @RequestMapping("/uploadFile")
    @ResponseBody
    public AjaxResult uploadFile(@RequestParam("files") MultipartFile[] file, @RequestParam("id") String id){
        String filePath= RuoYiConfig.getUploadPath();
        if (file==null){
            return AjaxResult.error("文件不能为空！");
        }

        try {
            for (int i=0;i< file.length;i++){
                String filePath1= FileUploadUtils.upload(filePath,file[i]);
                String[] split = filePath1.split("/");
                String s = split[1];
                String fileUrl=filePath+"/"+split[3]+"/"+split[4]+"/"+split[5]+"/"+split[6];
                File file1=new File();
                file1.setFileUrl(fileUrl);
                file1.setFileName(file[i].getOriginalFilename());
                file1.setFileAddress(Constants.FILE_PATH_PREFIX+filePath1.split(Constants.RESOURCE_PREFIX)[1].split(StringUtils.substring(RuoYiConfig.getUploadPath(),RuoYiConfig.getProfile().length()+1))[1]);
                file1.setId(Long.parseLong(id));
                fileService.updateFile(file1);
            }
        }catch (IOException e){
            e.printStackTrace();
            AjaxResult.error("上传文件失败！");
        }
        return AjaxResult.success("文件上传成功!");
    }

    //文件上传跳转页面
    @RequestMapping("/upload/{id}")
    public String uploadFile(@PathVariable("id") String id,ModelMap mmap){
        mmap.addAttribute("id",id);
        return prefix+"/upload";
    }


    //下载成功文件删除
    @RequestMapping("/delete")
    @ResponseBody
    public String delete(Long equipmentId,String userName,Integer state) {
        if (state == 1) {
            File file = fileService.selectFileByEquipmentIdAndUserName(equipmentId, userName);
            String fileUrl = file.getFileUrl();
            java.io.File ioFile = new java.io.File(fileUrl);
            if (ioFile.delete()) {
                return "1";
            } else {
                return "0";
            }
        }else {
            return "0";
        }
    }




//    @RequiresPermissions("system:file:view")
    @GetMapping()
    public String file()
    {
        return prefix + "/file";
    }

    /**
     * 查询文件列表
     */
//    @RequiresPermissions("system:file:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(File file)
    {
        startPage();
        // 获取当前的用户信息
        User currentUser = ShiroUtils.getSysUser();
        // 获取当前的用户名称
        String loginUser = currentUser.getLoginName();
        file.setUserName(loginUser);

//        List<File> files = fileService.selectList();
//        for (int i = 0; i < files.size(); i++) {
//            files.get(i).
//        }


        List<File> list = fileService.selectFileList(file);
        return getDataTable(list);
    }

    /**
     * 导出文件列表
     */
//    @RequiresPermissions("system:file:export")
    @Log(title = "文件", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(File file)
    {
        List<File> list = fileService.selectFileList(file);
        ExcelUtil<File> util = new ExcelUtil<File>(File.class);
        return util.exportExcel(list, "文件数据");
    }

    /**
     * 新增文件
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存文件
     */
//    @RequiresPermissions("system:file:add")
    @Log(title = "文件", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(File file)
    {
        String userName = file.getUserName();
        Long equipmentId = file.getEquipmentId();
        // 获取当前的用户信息
        User currentUser = ShiroUtils.getSysUser();
        // 获取当前的用户名称
        String loginUser = currentUser.getLoginName();
        if (!loginUser.equals(userName)){
            return AjaxResult.error("请输入本人的登录名称!");
        }
        List<Equipment> equipmentList = iEquipmentService.selectEquipmentByEquipmentIdAndUserName(equipmentId, userName);
        if (equipmentList.isEmpty()){
            return AjaxResult.error("该设备不存请重新输入！");
        }else {
            return toAjax(fileService.insertFile(file));
        }
    }

    /**
     * 修改文件
     */
//    @RequiresPermissions("system:file:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        File file = fileService.selectFileById(id);
        mmap.put("file", file);
        return prefix + "/edit";
    }

    /**
     * 修改保存文件
     */
//    @RequiresPermissions("system:file:edit")
    @Log(title = "文件", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(File file)
    {
        return toAjax(fileService.updateFile(file));
    }

    //获取文件地址
    @GetMapping("/selectAddress")
    @ResponseBody
    public String selectAddress( Long equipmentId, String userName){
        File file = fileService.selectFileByEquipmentIdAndUserName(equipmentId, userName);
        String fileAddress = file.getFileAddress();
        return fileAddress;
    }



    /**
     * 删除文件
     */
//    @RequiresPermissions("system:file:remove")
    @Log(title = "文件", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(fileService.deleteFileByIds(ids));
    }
}
